package com.hskn.hss.module.inspectionCfg.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.controller.BaseController;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.casesetissuesource.entity.CasesetIssueSource;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.costdictitem.entity.CostDictItem;
import com.hskn.hss.module.costdictitem.service.ICostDictItemService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.employeeCorrectRecord.mapper.EmployeeCorrectRecordMapper;
import com.hskn.hss.module.inspectionCfg.entity.TlInspectionCfg;
import com.hskn.hss.module.inspectionCfg.mapper.TlInspectionCfgMapper;
import com.hskn.hss.module.inspectionCfg.service.ITlInspectionCfgService;
import com.hskn.hss.module.inspectionCfg.to.*;
import com.hskn.hss.module.inspectionCfg.vo.InspectionCfgExcelInVO;
import com.hskn.hss.module.inspectionCfg.vo.InspectionCfgExcelOutVO;
import com.hskn.hss.module.inspectionCfg.vo.TlInspectionCfgDetailVO;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-06
 */
@Api(tags = {"-tl_inspection_cfg"}, description = "车辆年检费")
@Slf4j
@RestController
@RequestMapping("/hss/tlinspectioncfg")
public class TlInspectionCfgController extends BaseController {
    @Autowired
    private ITlInspectionCfgService tlInspectionCfgService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ICostDictItemService costDictItemService;
    @Autowired
    private ITlCarService carService;
    @Autowired
    private ITlCarTypeService carTypeService;

    /***
     * 新增
     * @param insertTlInspectionCfgTO
     * @return
     */
    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_inspection_cfg", bean = TlInspectionCfg.class, beanMapper = TlInspectionCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆年检费新增接口", notes = "车辆年检费新增")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult insert(@RequestBody @Validated InsertTlInspectionCfgTO insertTlInspectionCfgTO) {
        try {
            return toAjax(tlInspectionCfgService.insert(insertTlInspectionCfgTO));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    /**
     * 修改
     *
     * @param updateTlInspectionCfgTO
     * @return
     */
    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_inspection_cfg", idKey = "id", bean = TlInspectionCfg.class, beanMapper = TlInspectionCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆年检费修改接口", notes = "车辆年修改导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult update(@RequestBody @Validated UpdateTlInspectionCfgTO updateTlInspectionCfgTO) {
        try {
            return toAjax(tlInspectionCfgService.update(updateTlInspectionCfgTO));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    /***
     * 删除
     * @param forIdsTO
     * @return
     */
    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_inspection_cfg", idKey = "ids", bean = TlInspectionCfg.class, beanMapper = TlInspectionCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆年检费删除接口", notes = "车辆年检费删除")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "deleteByid", method = RequestMethod.POST)
    public AjaxResult deleteByid(@RequestBody @Validated ForIdsTO forIdsTO) {
        try {
            return toAjax(tlInspectionCfgService.deleteByid(forIdsTO));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    /**
     * 根据Id获取
     *
     * @param inspectionCfgTOForOnlyId
     * @return
     */
    @ApiOperation(value = "车辆年检费详情接口", notes = "车辆年检费详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "getbyid", method = RequestMethod.POST)
    public AjaxResult<Object> getbyid(@RequestBody @Validated TlInspectionCfgTOForOnlyId inspectionCfgTOForOnlyId) {
        TlInspectionCfgDetailVO tlInspectionCfg = null;
        try {
            tlInspectionCfg = tlInspectionCfgService.getDetailById(inspectionCfgTOForOnlyId);
            return AjaxResult.success(tlInspectionCfg);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }


    }

    /**
     * 获取列表
     *
     * @param inspectionCfgListForPageTO
     * @return
     */
    @ApiOperation(value = "年检费列表接口", notes = "车辆年检费列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "getlist", method = RequestMethod.POST)
    public AjaxResult getlist(@RequestBody @Validated InspectionCfgListForPageTO inspectionCfgListForPageTO) {
        try {
            return AjaxResult.success(tlInspectionCfgService.getList(inspectionCfgListForPageTO));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }

    /**
     * 车辆年检费导入接口
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_inspection_cfg", bean = TlInspectionCfg.class, beanMapper = TlInspectionCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆年检费导入接口", notes = "车辆年检费导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @ModelAttribute @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file = excelReaderTo.getFiles();
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlInspectionCfg> util = new ExcelUtil<TlInspectionCfg>(TlInspectionCfg.class);
            List<TlInspectionCfg> inspectionCfgList = util.importExcel(inputStream);
            if (inspectionCfgList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            tlInspectionCfgService.excelReader(inspectionCfgList);
            if (tlInspectionCfgService.saveBatch(inspectionCfgList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception exception) {
            exception.printStackTrace();
            return AjaxResult.fail();
        }

    }

    @ApiOperation(value = "车辆年检费导出接口", notes = "车辆年检费导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = InspectionCfgExcelOutVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody InspectionCfgListTO inspectionCfgListTo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((inspectionCfgListTo.getIds()!=null&&inspectionCfgListTo.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            //查询数据
            List<TlInspectionCfg> inspectionCfgList = tlInspectionCfgService.getTlInspectionCfgList(inspectionCfgListTo, format);
            //工具类实例化
            ExcelUtil<InspectionCfgExcelOutVO> util = new ExcelUtil<InspectionCfgExcelOutVO>(InspectionCfgExcelOutVO.class);
            //数据载体转换
            List<InspectionCfgExcelOutVO> inspectionCfgExcelOutVOList = JSONObject.parseArray(JSONObject.toJSONString(inspectionCfgList), InspectionCfgExcelOutVO.class).stream().sorted(Comparator.comparing(InspectionCfgExcelOutVO::getCosttime).reversed()).collect(Collectors.toList());
            //构造结果集
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            Map<String, CostDictItem> costDictItemMap = costDictItemService.getCostDictItemMap(new QueryWrapper<>());
            Map<String, TlCar> carMap = carService.getCarMap(new QueryWrapper<>());
            Map<String, TlCarType> carTypeMap = carTypeService.getCarTypeMap(new QueryWrapper<>());
            for (InspectionCfgExcelOutVO inspectionCfgExcelOutVO : inspectionCfgExcelOutVOList) {
                if (departMap.containsKey(inspectionCfgExcelOutVO.getDeptid())) {
                    inspectionCfgExcelOutVO.setDeptName(departMap.get(inspectionCfgExcelOutVO.getDeptid()).getDepartName());
                }
                if (costDictItemMap.containsKey(inspectionCfgExcelOutVO.getRepairreason())) {
                    inspectionCfgExcelOutVO.setRepairreasonName(costDictItemMap.get(inspectionCfgExcelOutVO.getRepairreason()).getCostname());
                }
                if (carMap.containsKey(inspectionCfgExcelOutVO.getCarnumid())) {
                    inspectionCfgExcelOutVO.setCarCardNum(carMap.get(inspectionCfgExcelOutVO.getCarnumid()).getCarnumber());
                }
                if (StringUtils.isNotEmpty(inspectionCfgExcelOutVO.getCosttime())) {
                    inspectionCfgExcelOutVO.setCosttimeString(format.format(inspectionCfgExcelOutVO.getCosttime()));
                }
                if(carTypeMap.containsKey(inspectionCfgExcelOutVO.getCartype())){
                    inspectionCfgExcelOutVO.setCartypename(carTypeMap.get(inspectionCfgExcelOutVO.getCartype()).getTypename());
                }
            }
            //            导出
            return util.exportExcel(inspectionCfgExcelOutVOList, "车辆年检");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }


    @ApiOperation(value = "车辆年检费导出模板接口", notes = "车辆年检费模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = InspectionCfgExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<InspectionCfgExcelInVO> util = new ExcelUtil<InspectionCfgExcelInVO>(InspectionCfgExcelInVO.class);
            //数据载体转换
            List<InspectionCfgExcelInVO> inspectionCfgExcelInVOList = new ArrayList<>();
            //导出
            return util.exportExcel(inspectionCfgExcelInVOList, "车辆年检模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

